﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Diagnostics;
using System.Threading;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace sqengine.Engine.Common
{
    public class NetworkAPI
    {
        private Game _game;

        private Thread _getexternalipthread;


        public NetworkAPI(Game game)
        {
            _game = game;
        }

        public void PrepareGetExternalIP(string output)
        {

            _getexternalipthread = new Thread(delegate()
            {
                GetExternalIp(output);
            });

            _getexternalipthread.Name = "update external ip thread";
            _getexternalipthread.Priority = ThreadPriority.Normal;
            _getexternalipthread.Start();

        }



        private void GetExternalIp(string output)
        {
            UriBuilder uri = new UriBuilder();
            bool have_proxy = false;

            if (!string.IsNullOrEmpty(GetProxyInformation()))
            {
                uri = new UriBuilder(GetProxyInformation());
                have_proxy = true;
            }

            string whatIsMyIp = "http://whatismyip.com";
            string getIpRegex = @"(?<=<h1>.*)\d*\.\d*\.\d*\.\d*(?=</h1>)";
            WebClient wc = new WebClient();

            if (have_proxy)
            {

                wc.Proxy = new WebProxy(uri.Host, uri.Port);
                if (!string.IsNullOrEmpty(uri.UserName))
                    wc.Proxy.Credentials = new NetworkCredential(uri.UserName, uri.Password);
            }

            UTF8Encoding utf8 = new UTF8Encoding();

            string requestHtml = string.Empty;

            try
            {
                requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
            }
            catch (WebException we)
            {
                // do something with exception
                Console.Write(we.ToString());
            }
            Regex r = new Regex(getIpRegex);
            Match m = r.Match(requestHtml.Replace("Your IP Address Is: ", string.Empty));
            IPAddress externalIp = null;
            if (m.Success)
            {
                externalIp = IPAddress.Parse(m.Value);
            }

            if (output != string.Empty)
            {
                ((sqengine)_game).ConsoleSetVar(output, externalIp);
            }
            else
            {
                ((sqengine)_game).Console.AddConsole(string.Format("External IP: {0}", externalIp));
            }

            _getexternalipthread = null;
        }

        public string GetInternalIp()
        {
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

            return localIPs[0].ToString();


        }
        private string GetProxyInformation()
        {
            bool p_enabled = false;
            bool.TryParse(((sqengine)_game).ConsoleGetVar(sqengine.VAR_SQPROXY_ENABLED), out p_enabled);

            if (p_enabled)
            {

                string url = ((sqengine)_game).ConsoleGetVar(sqengine.VAR_SQPROXY_URL);
                string usern = ((sqengine)_game).ConsoleGetVar(sqengine.VAR_SQPROXY_USER);
                string passwd = ((sqengine)_game).ConsoleGetVar(sqengine.VAR_SQPROXY_PASSWD);

                passwd = Functions.CheckPasswordString(passwd);

                return string.Format("http://{0}:{1}@{2}/", usern, passwd, url);

            }
            else
            {
                return string.Empty;
            }


        }


    }
}
